﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows.Media.Media3D;
using RobotGerchik.Config;
using RobotGerchik.DataClass.BaseTransaqCalss;
using RobotGerchik.DataClass.Gerchik;

namespace RobotGerchik.DataClass
{
    public class Data
    {
        public ObservableCollection<MoneyPosition> MoneyPositionList = new ObservableCollection<MoneyPosition>();
        public ObservableCollection<SecPosition> SecPositionList = new ObservableCollection<SecPosition>();

        public ObservableCollection<Securities> SecuritiesList = new ObservableCollection<Securities>();
        public ObservableCollection<GechikRobotItem> GechikRobotItemList = new ObservableCollection<GechikRobotItem>();
        public ObservableCollection<Candles> CandlesItems = new ObservableCollection<Candles>();
        public ObservableCollection<ClientAccount> ClietnAccountsList = new ObservableCollection<ClientAccount>();
        public ObservableCollection<Quotations> QuotationsList = new ObservableCollection<Quotations>();

        public ObservableCollection<Order> OrderList = new ObservableCollection<Order>();
        public ObservableCollection<StopOrder> StopOrderList = new ObservableCollection<StopOrder>();
        public ObservableCollection<Deal> DealList = new ObservableCollection<Deal>();
        public ObservableCollection<AllTrades> AllTrade = new ObservableCollection<AllTrades>();

        public TransaqCommands TransaqCommand = new TransaqCommands();


        /// <summary>
        /// Поиск нужных стоп-заявок
        /// </summary>
        /// <param name="p1"></param>
        /// <param name="p2"></param>
        /// <param name="p3"></param>
        /// <returns></returns>
        internal List<StopOrder> GetStopOrderListAllforInstrunemts(string account, string clientCode, string seccode)
        {
            List<StopOrder> stopOrders = new List<StopOrder>();

            foreach (var item in StopOrderList)
            {
                if (item.Client == clientCode && item.Seccode == seccode)
                {
                    item.Status = GetStatusesStopOrder(item.Status);
                    stopOrders.Add(item);
                }
            }
            return stopOrders;
        }

        /// <summary>
        /// Поиск активных стоп-заявок
        /// </summary>
        /// <param name="account"></param>
        /// <param name="clientCode"></param>
        /// <param name="seccode"></param>
        /// <returns></returns>
        internal List<StopOrder> GetStopOrderListAllforInstrunemtsActive(string account, string clientCode, string seccode)
        {
            List<StopOrder> stopOrders = new List<StopOrder>();

            foreach (var item in StopOrderList)
            {
                if (item.Client == clientCode && item.Seccode == seccode && item.Status == Cfg.Active)
                {
                    item.Status = GetStatusesStopOrder(item.Status);
                    stopOrders.Add(item);
                }
            }
            return stopOrders;
        }

        /// <summary>
        /// Переопределение статуса стоп-заявок
        /// </summary>
        /// <param name="status"></param>
        /// <returns></returns>
        public string GetStatusesStopOrder(string status)
        {

            switch (status)
            {
                case "sl_forwarding":
                    return Cfg.Active;
                    break;
                case "watching":
                    return Cfg.Active;
                    break;
                case "cancelled":
                    return Cfg.Cancel;
                    break;
                case "rejected":
                    return Cfg.Cancel;
                    break;
                case "disabled":
                    return Cfg.Cancel;
                    break;
                //стоп-заявка отклонена брокером
                case "denied":
                    return Cfg.BrokerCancel;
                    break;
                //выставлена в торговую систему
                case "linkwait":
                    return Cfg.AddToTs;
                    break;
                case "sl_executed":
                    return Cfg.Performed;
                    //исполенена тейк профит у связанной заявки
                case "tp_executed":
                    return Cfg.Performed;
                    break;
                default:
                    break;
            }

            return status;
        }

        /// <summary>
        /// Поиск нужных заявок
        /// </summary>
        /// <param name="account"></param>
        /// <param name="clientCode"></param>
        /// <param name="seccode"></param>
        /// <returns></returns>
        public List<Order> GetOrderListAllforInstrunemts(string account, string clientCode, string seccode)
        {
            List<Order> orders = new List<Order>();

            foreach (var item in OrderList)
            {
                if (item.Client == clientCode && item.Seccode == seccode)
                {
                    item.Status = GetStatusesOrder(item.Status);
                    orders.Add(item);
                }
            }
            return orders;
        }

        /// <summary>
        /// Определение активных заявок
        /// </summary>
        /// <param name="account"></param>
        /// <param name="clientCode"></param>
        /// <param name="seccode"></param>
        /// <returns></returns>
        public List<Order> GetOrderListAllforInstrunemtsActive(string account, string clientCode, string seccode)
        {
            List<Order> orders = new List<Order>();

            foreach (var item in OrderList)
            {
                if (item.Client == clientCode && item.Seccode == seccode && item.Status == Cfg.Active)
                {
                    item.Status = GetStatusesOrder(item.Status);
                    orders.Add(item);
                }
            }
            return orders;
        }

        /// <summary>
        /// Переопределение статуса
        /// </summary>
        /// <param name="status"></param>
        /// <returns></returns>
        public string GetStatusesOrder(string status)
        {

            switch (status)
            {
                case "none":
                    return Cfg.Unknown;
                    break;
                case "active":
                    return Cfg.Active;
                    break;
                case "cancelled":
                    return Cfg.Cancel;
                    break;
                //находится в процессе снятия
                case "withdrawtime":
                    return Cfg.Cancel;
                    break;

                case "matched":
                    return Cfg.Performed;
                    break;
                default:
                    break;
            }

            return status;
        }

        /// <summary>
        /// Получение полследней цены по инструменту
        /// </summary>
        /// <param name="seccode">инструмент</param>
        /// <returns>Цена последней сделки</returns>
        public double GetLastPrice(string seccode)
        {
            foreach (var item in QuotationsList)
            {
                if (item.Seccode == seccode)
                    return item.Last;
            }

            return 0;
        }

        /// <summary>
        /// Получение всех счетов
        /// </summary>
        /// <returns>Список клиентских счетов</returns>
        public List<string> GetClientCode()
        {
            List<string> result = new List<string>();

            if (ClietnAccountsList.Count > 0)
                foreach (var item in ClietnAccountsList)
                {
                    result.Add(item.ID);
                }

            return result;
        }

        /// <summary>
        /// Получаем список доступных рынков
        /// </summary>
        public List<string> GetMarkets()
        {
            List<string> result = new List<string>();

            if (MainWindow.DictionaryMarkets.Count > 0)
                foreach (var item in MainWindow.DictionaryMarkets)
                {
                    result.Add(item.Value);
                }

            return result;
        }


        /// <summary>
        /// Получаем доступные инструменты по выбранному рынку
        /// </summary>
        /// <returns></returns>
        public List<string> GetInstrumets(string market)
        {
            List<string> result = new List<string>();

            int tmpMarket = 0;
            if (MainWindow.DictionaryMarkets.Count > 0)
                foreach (var item in MainWindow.DictionaryMarkets)
                {
                    if (item.Value == market)
                        tmpMarket = item.Key;
                }

            if (SecuritiesList.Count > 0)
                foreach (var item in SecuritiesList)
                {
                    if (item.Market == tmpMarket)
                        result.Add(item.Seccode);
                }
            result.Sort();

            return result;

        }


        public string GetBoard(string seccode)
        {
            foreach (var item in SecuritiesList)
            {
                if (item.Seccode == seccode)
                    return item.Board;
            }

            return "";
        }

        /// <summary>
        /// Получаем доступные таймфреймы
        /// </summary>
        /// <returns></returns>
        public List<string> GetTimeFrame()
        {
            List<string> result = new List<string>();

            if (MainWindow.DictionaryTimeFrame.Count > 0)
                foreach (var item in MainWindow.DictionaryTimeFrame)
                {
                    result.Add(item.Value);
                }

            return result;

        }

        /// <summary>
        /// Получение точности цены, количество знаков после запятой
        /// </summary>
        /// <param name="seccode">инструмент</param>
        /// <returns>точность</returns>
        public int GetAccuraccy(string seccode)
        {
            foreach (var item in SecuritiesList)
            {
                if (item.Seccode == seccode)
                    return item.Decimals;
            }

            return 0;
        }

        /// <summary>
        /// Получение SecId по инструменту
        /// </summary>
        /// <param name="seccode"></param>
        /// <returns></returns>
        public int GetSecId(string seccode)
        {
            foreach (var item in SecuritiesList)
            {
                if (item.Seccode == seccode)
                    return item.Secid;
            }

            return 0;
        }



    }
}
